<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { $t } from '@/locales';
import { useRouterPush } from '@/hooks/common/router';
import { useForm, useFormRules } from '@/hooks/common/form';
import { useAuthStore } from '@/store/modules/auth';
import { getServiceBaseURL } from '@/utils/service';
import { localStg } from '@/utils/storage';
import { useTabStore } from '@/store/modules/tab';
const { otherBaseURL } = getServiceBaseURL(import.meta.env, true);
const PROXY_API = otherBaseURL.api;

defineOptions({ name: 'PwdLogin' });

const authStore = useAuthStore();
const { toggleLoginModule } = useRouterPush();
const { formRef, validate } = useForm();

const tabStore = useTabStore();

interface FormModel {
  userName: string;
  password: string;
  captcha: string;
}

const model = ref<FormModel>({
  userName: '',
  password: '',
  captcha: ''
});

// 是否显示验证码
const showCode = ref(false);

// 验证码图片url（请补充实际路径）
const captchaImgUrl = ref('');
// 刷新验证码方法（请补充实际逻辑）
function refreshCaptcha() {
  const time = Number(new Date());
  // 这里可以加时间戳或随机数防止缓存
  captchaImgUrl.value = `${PROXY_API}/user/verifyCode?uid=${model.value.userName}&t=${time}`;
}

const rules = computed<Record<keyof FormModel, App.Global.FormRule[]>>(() => {
  // inside computed to make locale ref, if not apply i18n, you can define it without computed
  const { formRules } = useFormRules();

  return {
    userName: formRules.userName,
    password: [{
      required: true,
      message: '请输入密码',
      trigger: 'change'
    }],
    captcha: [{
      required: true,
      message: '请输入验证码',
      trigger: 'change'
    }]
  };
});

// 处理用户名输入，不允许输入空格
function handleUserNameInput(value: string) {
  console.log(value)
  // 移除所有空格
  const filteredValue = value.replace(/\s/g, '');
  model.value.userName = filteredValue;
}

// 处理用户名变化事件，显示并刷新验证码
function handleUserNameChange(value: string) {
  if (value.trim() !== '') {
    showCode.value = true;
    refreshCaptcha();
  } else {
    showCode.value = false;
  }
}

async function handleSubmit() {
  await validate();
  const { loginToken, error } = await authStore.login(model.value.userName, model.value.password, model.value.captcha);
  // 登录失败时刷新验证码
  if (error) {
    refreshCaptcha();
  }
  console.log(loginToken, error);
}



onMounted(() => {
  setTimeout(() => {
    localStg.remove('globalTabs');
    tabStore.clearTabs();
  }, 50);
});
</script>

<template>
  <ElForm
    ref="formRef"
    :model="model"
    class="user-form"
    :rules="rules"
    size="large"
    :show-label="false"
    @keyup.enter="handleSubmit"
  >
    <ElFormItem prop="userName">
      <ElInput
        v-model.trim="model.userName"
        :placeholder="$t('page.login.common.userNamePlaceholder')"
        @input="handleUserNameInput"
        @change="handleUserNameChange"
      />
    </ElFormItem>
    <ElFormItem prop="password">
      <ElInput
        v-model="model.password"
        type="password"
        show-password-on="click"
        :placeholder="$t('page.login.common.passwordPlaceholder')"
      />
    </ElFormItem>
    <!-- 验证码输入区域 -->
    <ElFormItem v-if="showCode" prop="captcha">
      <div style="display: flex; align-items: center; width: 100%">
        <ElInput v-model="model.captcha" placeholder="请输入验证码" style="flex: 1; margin-right: 8px" />
        <img
          :src="captchaImgUrl"
          alt="captcha"
          title="点击刷新验证码"
          style="height: 36px; width: 80px; cursor: pointer; border-radius: 4px; border: 1px solid #eee"
          @click="refreshCaptcha"
        />
      </div>
    </ElFormItem>
    <ElSpace direction="vertical" :size="24" class="w-full" fill>
      <!--
 <div class="flex-y-center justify-between">
        <ElCheckbox>{{ $t('page.login.pwdLogin.rememberMe') }}</ElCheckbox>
      </div> 
-->
      <ElButton type="primary" size="large" round block :loading="authStore.loginLoading" @click="handleSubmit">
        {{ $t('common.confirm') }}
      </ElButton>
    </ElSpace>
  </ElForm>
</template>

<style>
.user-form {
  input:-webkit-autofill,
  input:-webkit-autofill:hover,
  input:-webkit-autofill:focus,
  input:-webkit-autofill:active {
    -webkit-box-shadow: 0 0 0 30px white inset !important; /* 修改背景色为白色 */
    -webkit-text-fill-color: black !important; /* 修改文本颜色为黑色 */
  }
}
</style>
